import time
from datetime import datetime
from kubernetes import client, config


def get_recent_events(interval_minutes=1, namespace=None):
    """
    定时获取Kubernetes事件信息
    :param interval_minutes: 获取间隔时间(分钟)
    :param namespace: 指定命名空间，None表示所有命名空间
    """
    # 加载kube配置
    try:
        config.load_kube_config(config_file="kube/config")
    except:
        config.load_incluster_config()

    v1 = client.CoreV1Api()
    last_check_time = datetime.utcnow()

    print(f"开始定时获取Kubernetes事件，间隔{interval_minutes}分钟...")
    print("=" * 80)

    while True:
        try:
            current_time = datetime.utcnow()
            print(f"\n当前时间：[ {datetime.now()} ]")
            print(f"\n检查时间范围: {last_check_time} - {current_time}")
            print("-" * 60)

            # 获取事件列表
            if namespace:
                events = v1.list_namespaced_event(namespace)
            else:
                events = v1.list_event_for_all_namespaces()

            # 筛选并打印最近interval_minutes分钟内的事件
            new_events = []
            for event in events.items:
                event_time = event.last_timestamp or event.event_time or event.metadata.creation_timestamp
                if event_time and event_time.replace(tzinfo=None) > last_check_time:
                    new_events.append(event)

            if not new_events:
                print("没有新事件")
            else:
                # 按时间排序
                new_events.sort(key=lambda e: (e.last_timestamp or e.event_time or e.metadata.creation_timestamp))
                for event in new_events:
                    print_event(event)

            # 更新最后检查时间并等待下一个周期
            last_check_time = current_time
            time.sleep(interval_minutes * 60)

        except Exception as e:
            print(f"获取事件时出错: {str(e)}")
            time.sleep(30)  # 出错后等待30秒再重试


def print_event(event):
    """格式化打印事件信息"""
    event_time = event.last_timestamp or event.event_time or event.metadata.creation_timestamp
    obj_ref = f"{event.involved_object.kind}/{event.involved_object.name}" if event.involved_object else "Unknown"
    print(f"{event_time} {event.type:7} {event.reason:20} {obj_ref:30} {event.message}")
    # print("=" * 80)
    # print(event)


if __name__ == "__main__":
    # 每隔3分钟检查一次，可以调整interval_minutes参数
    # 可以指定namespace如namespace="default"
    get_recent_events(interval_minutes=1, namespace=None)